﻿using Bookify.Application.Abstractions.Caching;
using Bookify.Domain.Abstractions;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bookify.Application.Abstractions.Behaviors
{
    internal sealed class QueryCachingBehavior<TRequest, TResponse>
        : IPipelineBehavior<TRequest, TResponse>
        where TRequest : ICachedQuery
        where TResponse : Result
    {
        private readonly ICacheService _cacheService;
        private readonly ILogger<QueryCachingBehavior<TRequest, TResponse>> _logger;

        public QueryCachingBehavior(
            ICacheService cacheService, 
            ILogger<QueryCachingBehavior<TRequest, TResponse>> logger)
        {
            _cacheService = cacheService;
            _logger = logger;
        }

        public async Task<TResponse> Handle(
            TRequest request, 
            RequestHandlerDelegate<TResponse> next, 
            CancellationToken cancellationToken)
        {
            TResponse? cacheResult = await _cacheService.GetAsync<TResponse>(
                request.CacheKey, 
                cancellationToken);

            string name = typeof(TRequest).Name;
            if (cacheResult != null)
            {
                _logger.LogInformation("{Query} 从缓存中获取结果", name);
                return cacheResult;
            }

            _logger.LogInformation("{Query} 缓存未命中", name);

            TResponse result = await next();

            if(result.IsSuccess)
            {
                await _cacheService.SetAsync(
                    request.CacheKey, 
                    result, 
                    request.Expiration, 
                    cancellationToken);
            }

            return result;
        }
    }
}
